<?php

namespace App\Utils;

class ToolUtil
{
    public static function api_curl($url, $post, $header = [], $timeout = 30, $formUrlencoded = false)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        if (!empty($header)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }
        if ($post) {
            curl_setopt($curl, CURLOPT_POST, true);
            //华为的参数是全部要urlcode，所以加了这个http_build_query
            if ($formUrlencoded) {
                $post = http_build_query($post);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
            } else {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
            }
        }
        $res = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            $msg = $url . '--' . curl_error($curl);//捕抓异常
            LoggerUtil::write('api_curl', $msg);
        }
        curl_close($curl); // 关闭CURL会话
        return $res; // 返回数据，json格式
    }

}